<?php
namespace Andorra\dao;

use Andorra\exceptions\KeyNotFoundException;
use Andorra\drivers\DataValidator;

class EntitySet implements \Iterator, \ArrayAccess {
	private $entityType;
	private $datasource;
	private $entities;
	private $pos = 0;
	
	public function __construct(EntityType $et, DataValidator $datasource) {
		$this->entityType = $et;
		$this->datasource = $datasource;
	}
	
	// Iterator interface methods
	public function current() {
		return $this->entities[$this->pos];
	}
	
	public function key() {
		return $this->pos;
	}
	
	public function next() {
		$this->pos++;
	}
	
	public function rewind() {
		// Load all data from the source, because we're doing a foreach
		$data = $this->datasource->getEntities($this->entityType);
		
		foreach ($data as $entity)
			$this->entities[] = new Entity($this->entityType, $entity);
		
		$this->pos = 0;
	}
	
	public function valid() {		
		return isset($this->entities[$this->pos]);
	}
	
	// ArrayAccess interface methods
	public function offsetGet($offset) {
		$data = $this->datasource->getEntityById($this->entityType, $offset);
			
		return new Entity($this->entityType, $data);
	}
	
	public function offsetExists($offset) { }
	
	public function offsetSet($offset, $value) { }
	
	public function offsetUnset($offset) { }
}
?>